//
//  CustomLayout.m
//  15-homework-Customlayout-wangyi
//
//  Created by 王道林 on 16/8/3.
//  Copyright © 2016年 王道林. All rights reserved.
//

#import "CustomLayout.h"

@interface CustomLayout ()
@property (nonatomic, assign) CGFloat contentWidth;
@property (nonatomic, strong) NSMutableArray<UICollectionViewLayoutAttributes *> *marrAttribute;
@property (nonatomic, assign) CGFloat itemHeight;

@end

@implementation CustomLayout


- (instancetype)init
{
    self = [super init];
    if (self) {
        _cellMargin = 30;
        _sectionInsert = 5;
        _marrAttribute = [NSMutableArray array];
    }
    return self;
}

- (CGFloat)itemHeight
{
    return CGRectGetHeight(self.collectionView.frame) - 2 * _sectionInsert;
}


- (void)prepareLayout
{

    // 记录width
    _contentWidth = _sectionInsert;
    
//    self.contentWidth = 0.0f;

    if (_marrAttribute.count != 0) {
        [_marrAttribute removeAllObjects];
    }
    
    for (int i = 0; i < [self.collectionView numberOfItemsInSection:0]; i++) {
    
        UICollectionViewLayoutAttributes *layoutAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        
        CGFloat x = _contentWidth ;
        NSLog(@"%lf", x);
        CGFloat y = _sectionInsert;
        NSLog(@"%lf", y);
        CGFloat width = [self.delegate collectionView:self.collectionView layout:self heightForItemAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        NSLog(@"%lf", width);
        CGFloat height = self.itemHeight;
        NSLog(@"%lf", height);
        layoutAttributes.frame = CGRectMake(x, y, width, height);
        [_marrAttribute addObject:layoutAttributes];
        
        _contentWidth = x + width + _cellMargin;
        
    
    }
    
    
  //  NSLog(@"%lf",_contentWidth);
}


- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
    return _marrAttribute;
}
    


- (CGSize)collectionViewContentSize
{
    return CGSizeMake(_contentWidth, 0);
}



@end
